package com.zhuiyun.project.api.recipe.service.impl;

import com.zhuiyun.project.api.recipe.mapper.RecipeMapper;
import com.zhuiyun.project.api.recipe.model.RecipeModel;
import com.zhuiyun.project.api.recipe.service.RecipeService;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.UploadFileUtils;
import com.zhuiyun.project.utils.pageUtil.MybatisPageHelper;
import com.zhuiyun.project.utils.pageUtil.PageRequest;
import com.zhuiyun.project.utils.pageUtil.PageResult;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class RecipeServiceImpl implements RecipeService {
    @Resource
    RecipeMapper recipeMapper;

    @Override
    public CommonResult getRevipeByPage(RecipeModel recipeModel, PageRequest pageRequest) {
        // 设置分页
        MybatisPageHelper.startPage(pageRequest);
        PageResult pageResult = MybatisPageHelper.getPageResult(recipeMapper.getRevipeByPage(recipeModel));
        return CommonResult.ok(pageResult);
    }

    @Override
    public CommonResult addRecipe(RecipeModel recipeModel, MultipartFile file) {
        String s = UploadFileUtils.uploadFile(file);
        recipeModel.setRecipeType(0);
        recipeModel.setDelFlag(0);
        recipeModel.setCreateTime(new Date());
        recipeModel.setUpdateTime(new Date());
        recipeModel.setRecipeFileId(Integer.valueOf(s));
        Integer integer = recipeMapper.addRecipe(recipeModel);
        if (integer >= 1) {
            return CommonResult.ok(EmErrorCode.SAVE_OK);
        }else {
            return CommonResult.ok(EmErrorCode.SAVE_ERROR);
        }
    }

    @Override
    public CommonResult updateRecipe(RecipeModel recipeModel, MultipartFile file) {
        if (file != null) {
            String s = UploadFileUtils.uploadFile(file);
            recipeModel.setRecipeFileId(Integer.valueOf(s));
        }
        recipeModel.setUpdateTime(new Date());
        recipeModel.setDelFlag(0);
        Integer integer = recipeMapper.updateRecipe(recipeModel);
        if (integer >= 1) {
            return CommonResult.ok(EmErrorCode.UPDATE_OK);
        }else {
            return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
        }
    }

    @Override
    public CommonResult deleteRecipe(Integer id) {
        Integer i = recipeMapper.deleteRecipe(id);
        if (i>0) {
            return CommonResult.ok(EmErrorCode.DELETE_OK);
        }else {
            return CommonResult.error(EmErrorCode.DELETE_ERROR);
        }
    }
}
